<?php

namespace addons\venue\controller;

use app\admin\model\venue\user\Balance;
use app\admin\model\venue\user\Log;
use app\admin\model\venue\user\Store;
use app\admin\model\venue\venue\Reserve;
use app\common\controller\Api;
use think\Request;


class Businuss extends Api
{
    // 无需登录的接口,*表示全部
    protected $noNeedLogin = [];
    protected $noNeedRight = ['*'];
    protected $user_id = "";

    public function __construct(Request $request = null)
    {
        parent::__construct($request);
        $this->user_id = $this->auth->id;
        //校验权限
        if (!Store::get(["user_id"=>$this->user_id,"status"=>"normal"])){
            $this->error("暂无权限");
        }
    }

    /*
     * 获取商家信息
     */
    public function store_info(){
        $user_id = $this->auth->id;
        $data = [];
        //查询绑定的场馆
        $store = Store::get(["user_id"=>$user_id,"status"=>"normal"]);
        if (!$store){
            $this->error("暂无权限");
        }
        $venue = \app\admin\model\venue\venue\Venue::get($store['venue_id']);
        //余额
        $data['money'] = $venue['money'];

        //今日营业额
        $data['top'][0]['key'] = '今日营业额';
        $data['top'][0]['value'] = bcsub(Balance::whereTime("createtime",'d')->where(["type"=>1,"venue_id"=>$venue["id"]])->sum("money"),Balance::whereTime("createtime",'d')->where(["type"=>2,"venue_id"=>$venue["id"]])->sum("money"),2);
        //今日订单
        $data['top'][1]['key'] = '今日订单';
        $data['top'][1]['value'] = \app\admin\model\venue\order\Order::where("status",">",1)->where("venue_id",$venue["id"])->whereTime("createtime",'d')->count();
        //pv
        $data['top'][2]['key'] = 'pv';
        $data['top'][2]['value'] = Log::count();
        //uv
        $data['top'][3]['key'] = 'uv';
        $data['top'][3]['value'] = Log::group('user_id')->count();
        //积分订单数
//        $data['below'][0]['key'] = '积分订单数';
//        $data['below'][0]['value'] = \app\admin\model\venue\order\Order::where(["order_type"=>1])->where("status",">",1)->count();
        //商品订单数
        $data['below'][1]['key'] = '商品订单数';
        $data['below'][1]['value'] = \app\admin\model\venue\order\Order::where(["order_type"=>2,"venue_id"=>$venue["id"]])->where("status",">",1)->count();
        //课程订单数
        $data['below'][2]['key'] = '课程订单数';
        $data['below'][2]['value'] = \app\admin\model\venue\order\Order::where(["order_type"=>3,"venue_id"=>$venue["id"]])->where("status",">",1)->count();
        //活动订单数
        $data['below'][3]['key'] = '活动订单数';
        $data['below'][3]['value'] = \app\admin\model\venue\order\Order::where(["order_type"=>4,"venue_id"=>$venue["id"]])->where("status",">",1)->count();
        $this->success("success",$data);
    }

    /*
     * 余额明细列表
     */
    public function balance(){
        $user_id = $this->auth->id;
        $page   = $this->request->post('page')??1;  //页码
        $limit  = $this->request->post('limit')??10; //每页显示条数
        $date  = $this->request->post('date')??""; //年月
        //查询绑定的场馆
        $store = Store::get(["user_id"=>$user_id,"status"=>"normal"]);
        if (!$store){
            $this->error("暂无权限");
        }
        $venue = \app\admin\model\venue\venue\Venue::get($store['venue_id']);
        if ($date){
            $data = Balance::where('FROM_UNIXTIME(createtime,"%Y-%m")="'.$date.'"')->where(["venue_id"=>$venue["id"]])->order("id","desc")->paginate(["page"=>$page,"list_rows"=>$limit])
                ->each(function ($item){
                    if ($item->user_id){
                        $user  = \app\admin\model\User::get($item->user_id);
                        if ($user){
                            $item->username = $user['username'];
                        }else{
                            $item->username = "未知";
                        }
                    }else{
                        $item->username = "未知";
                    }

                });
        }else{
            $data = Balance::where(["venue_id"=>$venue["id"]])->order("id","desc")->paginate(["page"=>$page,"list_rows"=>$limit])
                ->each(function ($item){
                    if ($item->user_id){
                        $user  = \app\admin\model\User::get($item->user_id);
                        if ($user){
                            $item->username = $user['username'];
                        }else{
                            $item->username = "未知";
                        }
                    }else{
                        $item->username = "未知";
                    }
                });
        }
        $this->success("success",$data);
    }

    //记录请求
    public function add_log(){
        $user_id = $this->request->post('user_id')??0;
        $url = $this->request->post('url')??"";
        $phone_config = $this->request->post('phone_config/a');
        if (empty($phone_config)){
            $this->error("手机配置不能为空");
        }
        $ip = request()->ip();
        if ($user_id){
            $user = \app\admin\model\User::get($user_id);
            $username = $user['username'];
        }else{
            $username = "";
        }
        Log::create([
            "user_id"=>$user_id,
            "username"=>$username,
            "logintime"=>time(),
            "daytime"=>strtotime(date("Y-m-d")),
            "loginip"=>$ip,
            "url"=>$url,
            "system"=>$phone_config['system'],
            "system_md5"=>md5(json_encode($phone_config)),
            "phone_model"=>json_encode($phone_config),
            "createtime"=>time(),
            "updatetime"=>time(),
        ]);
        $this->success("success");

    }

    /*
     * 核销二维码
     */
    public function hx_code(){
        $user_id = $this->auth->id;
        $order_no = $this->request->post('order_no');
        $code = $this->request->post('code');
        //查询绑定的场馆
        $store = Store::get(["user_id"=>$user_id,"status"=>"normal"]);
        if (!$store){
            $this->error("暂无权限");
        }
        $venue = \app\admin\model\venue\venue\Venue::get($store['venue_id']);
        if (!$code){
            $this->error("缺少核销码");
        }
        if ($order_no){
            $order = \app\admin\model\venue\order\Order::get(["order_no"=>$order_no,"venue_id"=>$venue["id"]]);
            if (!$order){
                $this->error("订单不存在");
            }
            if ($order['order_type']==2){
                $reserve = Reserve::get(['order_id'=>$order['id'],"hx_code"=>$code]);
                if (!$reserve){
                    $this->error("核销码错误");
                }
                //判断是否过期
                if (time()>strtotime($reserve['fixed_date']." ".$reserve['start_times'])){
                    $this->error("已过预定时间");
                }
                $reserve->write = 1;
                $reserve->is_cl = 1;
                $reserve->save();
                $reserve_hx = Reserve::where(['order_id'=>$order['id'],"is_cl"=>0])->find();
                if (!$reserve_hx){
                    //查看有没有退款的场次
                    $reserve_hxs = Reserve::where(['order_id'=>$order['id'],"is_cl"=>1,"refund"=>1])->find();
                    if ($reserve_hxs){
                        $order->status = 5;
                        $order->bf_refund = 1;
                        $order->save();
                    }else{
                        $order->status = 3;
                        $order->write = 1;
                        $order->save();
                    }

                }
            }else{
                $order->status = 3;
                $order->write = 1;
                $order->save();
            }
        }else{
            $reserve = Reserve::get(["hx_code"=>$code]);
            if ($reserve && $reserve['venue_id'] == $venue['id']){
                $reserve->is_cl = 1;
                $reserve->write = 1;
                $reserve->save();
                $reserve_hx = Reserve::where(['order_id'=>$reserve['order_id'],"is_cl"=>0])->find();
                if (!$reserve_hx){
                    //查看有没有退款的场次
                    $reserve_hxs = Reserve::where(['order_id'=>$reserve['order_id'],"is_cl"=>1,"refund"=>1])->find();
                    $order = \app\admin\model\venue\order\Order::get(["hx_code"=>$code]);

                    if ($reserve_hxs){
                        $order->status = 5;
                        $order->bf_refund = 1;
                        $order->save();
                    }else{
                        $order->status = 3;
                        $order->write = 1;
                        $order->save();
                    }

                }
            }else{
                $order = \app\admin\model\venue\order\Order::get(["hx_code"=>$code,"venue_id"=>$venue["id"]]);
                if (!$order){
                    $this->error("核销码不正确");
                }else{
                    $order->status = 3;
                    $order->write = 1;
                    $order->save();
                }
            }
        }
        $this->success("核销成功");
    }

    /*
     * 获取订单类型
     */
    public function order_type(){
        $order = new \app\admin\model\venue\order\Order();
        $type = $order->getOrderTypeList();
        $arr = [];
        foreach ($type as $tk => $tv){
            if ($tk == 1){
                continue;
            }
            $arr[$tk]['type'] = $tk;
            $arr[$tk]['name'] = $tv;
        }
        $this->success("success",array_merge($arr));
    }



}
